package com.itheima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.dto.ArticleHomeDto;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.mapper.ApArticleConfigMapper;
import com.itheima.article.mapper.ApArticleContentMapper;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.mapper.ApArticleMapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.article.vo.ArticleInfoVo;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.dto.PageRequestDto;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.fagin.AdWmNewsFeign;
import com.itheima.wemedia.pojo.WmNews;
import jdk.nashorn.internal.scripts.JS;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.invoke.LambdaConversionException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @description <p>已发布的文章信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.article.service.impl
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

   @Autowired
   private ApArticleConfigMapper apArticleConfigMapper;
   @Autowired
   private ApArticleContentMapper apArticleContentMapper;

   //注入远程调用自媒体微服务
   @Autowired
   private AdWmNewsFeign adWmNewsFeign;

    /**
     * 远程调用添加文章数据
     *
     * @param articleInfoDto
     * @return
     */
    @Override
    @Transactional
    public ResultVo addArticleInfo(ArticleInfoDto articleInfoDto) {
        ApArticle apArticle = articleInfoDto.getApArticle();
        //获取文章id，判断是否是添加文章的请求
        Long id = apArticle.getId();
        //如果id不为null表示是修改文章信息，需要删除掉就文章的信息
        if (id!=null){
            /*removeById(id);
            //删除文章配置表的数据
            apArticleConfigMapper.deleteById(id);
            //删除内容表中的数据
            apArticleContentMapper.deleteById(id);
            //将id设置为null再次新增产生新的id*/
            //将文章配置表，删除改为已删除
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsDelete(1);
            apArticleConfig.setId(id);
            apArticleConfigMapper.updateById(apArticleConfig);
            apArticle.setId(null);
        }
        //添加文章到数据库
        boolean save = save(articleInfoDto.getApArticle());
        if (!save){
            throw new LeadNewsException("添加已发布文章到数据库失败！");
        }
        //获取已发布文章配置，将id全部设置为文章id
        ApArticleConfig apArticleConfig = articleInfoDto.getApArticleConfig();
        apArticleConfig.setId(apArticle.getId());
        apArticleConfig.setArticleId(apArticle.getId());
        //添加已发布文章配置到数据库
        int insert = apArticleConfigMapper.insert(apArticleConfig);
        //判断是否添加成功，失败则抛出异常
        if (insert<0){
            throw new LeadNewsException("添加已发布文章配置失败！");
        }
        //获取已发布文章内容，将id全部设置为文章id
        ApArticleContent apArticleContent = articleInfoDto.getApArticleContent();
        apArticleContent.setId(apArticle.getId());
        apArticleContent.setArticleId(apArticle.getId());
        int row = apArticleContentMapper.insert(apArticleContent);
        //判断是否添加已发布文章成功
        if (row<=0){
            throw new LeadNewsException("添加文章内容失败");
        }
        //创建自媒体文章对象
        WmNews wmNews = new WmNews();
        //设置文章库存储的文章id
        wmNews.setArticleId(apArticle.getId());
        //设置状态为已发布状态
        wmNews.setStatus(BusinessConstants.WmNewsConstants.STATUS_PUBLISHED);
        //设置要更新的文章id
        wmNews.setId(articleInfoDto.getWmNewsId());
        //更新为上架状态
        wmNews.setEnable(BusinessConstants.WmNewsConstants.WM_COVER_REFERENCE);
        ResultVo resultVo = adWmNewsFeign.updateWmNews(wmNews);
        if (!resultVo.isSuccess()){
            throw new LeadNewsException("远程调用自媒体微服务更新数据失败");
        }
        return ResultVo.ok();
    }

    /**
     * 上下架同步，到文章库
     *
     * @param value
     */
    @Override
    public boolean apConsumer(String value) {
        //将传过来的参数解析为对象
        JSONObject jsonObject = JSON.parseObject(value);
        //获取解析对象中的文章id,和上下架状态
        Long apArticleId = jsonObject.getLong("article");
        Long enable = jsonObject.getLong("enable");
        //创建一个ApArticleConfig对象，设置id将上下加架状态进行更新
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setId(apArticleId);
        apArticleConfig.setIsDown(enable==1 ? 0:1);
        int row = apArticleConfigMapper.updateById(apArticleConfig);
        if (row<=0){
            return false;
        }
        //创建一个文章对象
        WmNews wmNews = new WmNews();
        //根据文章id查询文章对象
        ApArticle apArticle = getById(apArticleId);
        return true;
    }

    /**
     * app端文章分页查询
     * @param homeDto 接收前端传来的查询条件参数
     * @return 返回分页查询的结果
     */
    @Override
    public PageResultVo findPage(ArticleHomeDto homeDto, Integer loadType) {
        //参数检查，判断分页参数，不能过大影响服务器性能
        homeDto.checkSize();
        //判断最大时间是否有值，没有值为空，则把当前时间赋值上去
        if (homeDto.getMaxBehotTime()==null){
            homeDto.setMaxBehotTime(new Date());
        }
        //判断最小时间是否有值，没有值为空，则把当前时间赋值上去
        if (homeDto.getMinBehotTime()==null){
            homeDto.setMinBehotTime(new Date());
        }
        IPage<ApArticle> iPage = new Page<>(homeDto.getLoaddir(),homeDto.getSize());
        List<ApArticle> list = getBaseMapper().findPage(iPage, homeDto, loadType);
        return PageResultVo.pageResult(homeDto.getLoaddir(),homeDto.getLoaddir(),iPage.getTotal(),list);
    }

    /**
     * app端文章详情展示
     *
     * @param articleId
     * @return 返回封装数据
     */
    @Override
    public ArticleInfoVo findArticleInfoVo(Long articleId) {
        //根据传过来的文章id查询，文章配置表，获取文章配置对象
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectById(articleId);
        //根据文章id查询文章内容对象，获取文章内容对象
        ApArticleContent apArticleContent = apArticleContentMapper.selectById(articleId);
        //创建vo对象
        ArticleInfoVo articleInfoVo = new ArticleInfoVo();
        //将获取到的文章内容和文章配置对象封装到vo对象中
        articleInfoVo.setConfig(apArticleConfig);
        articleInfoVo.setContent(apArticleContent);
        //返回封装的vo对象
        return articleInfoVo;
    }
}
